package com.wicket.okrframework.biz.service.nb;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wicket.okrframework.biz.service.dto.common.SoftwareAuthorizationDto;
import com.wicket.okrframework.common.exception.BizException;
import com.wicket.okrframework.common.util.CommonFunctionHelper;
import com.wicket.okrframework.common.util.GitTools;
import lombok.Data;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Tags;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.stereotype.Service;
import com.wicket.okrframework.biz.service.dto.req.QueryReceiveFieldDetailReqDto;
import com.wicket.okrframework.biz.service.dto.res.QueryReceiveFieldDetailRespDto;
import com.wicket.okrframework.biz.service.dto.req.AddGenerateLicenseReqDto;
import com.wicket.okrframework.biz.service.dto.res.AddGenerateLicenseRespDto;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ： 手工接入方法
 * @since 2022/5/28 15:32
 *
 *
 * @version 1.0
 */
@Service
public class NbSecurity {
/**
      * code:receptionService
      * name:M1-接收出参字段
      * desc:undefined
      * gen by moon at 5/12/2023, 6:52:29 PM
      * 
      **/
     @Trace(operationName = "M1-接收出参字段")
     @Tags({@Tag(key = "参数",value = "arg[0]"),
     @Tag(key = "返回值",value = "returnedObj")})
      public QueryReceiveFieldDetailRespDto queryReceiveFieldDetail(QueryReceiveFieldDetailReqDto reqDto) {
        return BeanUtil.toBean(reqDto,QueryReceiveFieldDetailRespDto.class);
      }

      @Data
    class LicenseCreateReqDTO {
        private Map<String,SoftwareAuthorizationDto> info = new HashMap<>();
        private String mac;
        private String branchName;
    }

/**
      * code:generateLicense
      * name:M1新增生成License（特殊方法）
      * desc:undefined
      * gen by moon at 5/13/2023, 9:07:35 PM
      *
      **/
     @Trace(operationName = "M1新增生成License（特殊方法）")
     @Tags({@Tag(key = "参数",value = "arg[0]"),
     @Tag(key = "返回值",value = "returnedObj")})
      public AddGenerateLicenseRespDto addGenerateLicense(AddGenerateLicenseReqDto reqDto) {
         AddGenerateLicenseRespDto retData = new AddGenerateLicenseRespDto();
         LicenseCreateReqDTO customData = new LicenseCreateReqDTO();
         customData.setBranchName("license_"+CommonFunctionHelper.date2Str2(new Date()));
         for(SoftwareAuthorizationDto one : reqDto.getSoftwareAuthorizationList()){
             customData.getInfo().put(one.getAuthorizationKeyTypeCode(),one);
         }

         String username = "huruizhe";
         String password = "abc5509555";
         String dirPath = "licensetmp";
         String clonePath = "licensetmp";
         String httpsUrl = "https://codeup.aliyun.com/union8/okr/license.git";

         String branchName = "license_"+customData.getBranchName();
         //删除本地目录
         GitTools.deleteFolder(new File(dirPath));
         //克隆
         if (GitTools.cloneGit(httpsUrl, clonePath, username, password)) {
//             log.info("clone完成\n目录：" + clonePath);
         } else {
             throw new BizException("-1","制作lincense时，克隆代码失败",false);
         }

         //创建分支
         if (GitTools.createBranch(branchName, clonePath,username,password)) {
//             log.info("创建新分支成功\n分支名：dev");
         } else {
             throw new BizException("-1","制作lincense时，创建分支失败",false);
         }

         //checkout刚刚创建的分支
         GitTools.checkoutGit(clonePath, branchName,username, password);

         String cfile = "#include \"douliwan.h\"\n" +
                 "#include \"string.h\"\n" +
                 "\n" +
                 "JNIEXPORT jstring JNICALL Java_com_douliwan_DouliwanHeader_loadInfo\n" +
                 "  (JNIEnv *env, jclass jc) {\n" +
                 "      const char *wd = @config;\n" +
                 "      jstring out= (*env)->NewStringUTF(env,wd);\n" +
                 "      return out;\n" +
                 "  }";

         String data = JSON.toJSONString(customData);
         data = JSONObject.toJSONString(data);
         String replaceConfig = cfile.replace("@config",data);

         GitTools.writeUsingOutputStream(data,"licensetmp/douliwan/src/main/resources/content.txt");
         GitTools.writeUsingOutputStream(replaceConfig,"licensetmp/douliwan/src/main/resources/douliwan.c");

         String hfile = "/* DO NOT EDIT THIS FILE - it is machine generated */\n" +
                 "#include <jni.h>\n" +
                 "/* Header for class com_douliwan_DouliwanHeader */\n" +
                 "\n" +
                 "#ifndef _Included_com_douliwan_DouliwanHeader\n" +
                 "#define _Included_com_douliwan_DouliwanHeader\n" +
                 "#ifdef __cplusplus\n" +
                 "extern \"C\" {\n" +
                 "#endif\n" +
                 "/*\n" +
                 " * Class:     com_douliwan_DouliwanHeader\n" +
                 " * Method:    loadInfo\n" +
                 " * Signature: ()Ljava/lang/String;\n" +
                 " */\n" +
                 "JNIEXPORT jstring JNICALL Java_com_douliwan_DouliwanHeader_loadInfo\n" +
                 "  (JNIEnv *, jobject);\n" +
                 "\n" +
                 "#ifdef __cplusplus\n" +
                 "}\n" +
                 "#endif\n" +
                 "#endif";

         GitTools.writeUsingOutputStream(hfile,"licensetmp/douliwan/src/main/resources/douliwan.h");

         //提交代码到新分支
         if (GitTools.commitAndPush(new File(clonePath), username, password, "license制作")) {
//             log.info("提交成功");
         } else {
             throw new BizException("-1","制作lincense时，提交代码失败",false);
         }

         GitTools.deleteFolder(new File(dirPath));
         retData.setCodeHeaderText(hfile);
         retData.setCodeImplementText(replaceConfig);
         return retData;
      }
  //手工接入方法
}
